
#include "CGraphics.h"
#include "cmath"

CGraphics::CGraphics()
{
    sm = 0;
    in = 0;
}

CGraphics::~CGraphics()
{
}

void CGraphics::initializeGL()
{
    glDisable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);

    glEnable(GL_TEXTURE_2D);
    glColor4f(1.0f,1.0f,1.0f,1.0f);
    glEnable(GL_BLEND);
    glEnable(GL_ALPHA_TEST);
    glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
    glAlphaFunc(GL_GREATER,0.1f);
    glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
    glEnable(GL_LINE_SMOOTH);
}

void CGraphics::resizeGL(int w, int h)
{
    double nr = 700.0/500.0;
    double ar = (double)w/(double)h;
    double x0, x1, y0, y1;
    if ( ar > nr ) {
        y0 = 500; y1 = 0.0;
        sy = sx = 500.0/h;
        double dx = 500*ar - 700;
        x0 = 0-dx/2.0; x1 = 700+dx/2.0;
    } else {
        x0 = 0.0; x1 = 700.0;
        sy = sx = 700.0/w;
        double dx = 700/ar - 500;
        y0 = 500+dx/2.0; y1 = 0.0-dx/2.0;
    }

    x = x0; y = y0;
    if ( in != 0 )
        in->setScaPos( x0, y1, sx, sy);

    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(x0,x1,y0,y1,-100.0,100.0);
    glMatrixMode(GL_MODELVIEW);
    glClearColor(0.0f,0.0f,0.0f,1.0f);
}

void CGraphics::setScreenManger(CScreenManager *sm, CInput *in )
{
    this->sm = sm;
    this->in = in;
}

void CGraphics::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    foreach ( texLoad t, tl ) {
        *t.texture = bindTexture( QPixmap(t.name), GL_TEXTURE_2D );
        glBindTexture( GL_TEXTURE_2D, *t.texture );
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    }

    if ( sm != 0 )
        sm->draw( this );

    tl.clear();

    glFlush();
}

void CGraphics::loadTexture( const QString &file, GLuint &texture )
{
    texLoad t = {file,&texture};
    tl.append(t);
}

void CGraphics::renderTexts( double x, double y, QString text, QFont font )
{
    font.setPointSizeF(font.pointSizeF()/sx);
    this->renderText( (x-this->x)/sx, (y-500+this->y)/sy, text, font );
}
